<template>
  <div :class="className" :style="{height, width}" />
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { debounce } from '@/utils/index.js'

const props = defineProps({
  className: {
    type: String,
    default: 'chart-pie'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  },
  chartData: {
    type: Object,
    required: true
  }
})

const chart = ref(null)
let resizeHandler = null

const setOptions = (charData) => {
  chart.value.setOption({
    title: {
      text: '成功比例图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      left: 'center',
      bottom: '0',
    },
    calculable: true,
    series: [
      {
        name: '成功比例图',
        type: 'pie',
        roseType: 'radius',
        radius: [15, 95],
        center: ['50%', '50%'],
        data: [
          {value: charData.jobSuccess, name: '成功'},
          {value: charData.jobFail, name: '失败'},
          {value: charData.jobRunning, name: '进行中'}
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2600
      }
    ]
  })
}

const initChart = () => {
  chart.value = echarts.init(document.querySelector(`.${props.className}`), 'macarons')
  setOptions(props.chartData)
}

watch(() => props.chartData, (val) => {
  setOptions(val)
}, { deep: true })

onMounted(() => {
  initChart()
  resizeHandler = debounce(() => {
    if (chart.value) {
      chart.value.resize()
    }
  }, 100)
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  window.removeEventListener('resize', resizeHandler)
  chart.value.dispose()
  chart.value = null
})
</script>

<style lang="scss" scoped>
.el-col-lg-8 {
  width: 50%;
}
</style>
